<?php

namespace app\adminapi\controller;

use app\model\OperationLogModel;
use Webman\Http\Request;

class OperationLog extends BaseAdminApi
{
    /**
     * 不需要权限验证的方法
     * @var array
     */
    protected $noNeedPermission = [];

    /**
     * 获取操作日志列表
     */
    public function getLogs(Request $request)
    {
        $params = $request->get();
        
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $method = $params['method'] ?? '';
        $controller = $params['controller'] ?? '';
        $isSuccess = $params['is_success'] ?? '';
        $startDate = $params['start_date'] ?? '';
        $endDate = $params['end_date'] ?? '';
        $adminId = $params['admin_id'] ?? '';
        $userType = $params['user_type'] ?? '';
        $userId = $params['user_id'] ?? '';
        
        $query = OperationLogModel::with([
            'admin' => function($query) {
                $query->select('id', 'username', 'real_name');
            },
            'user' => function($query) {
                $query->select('id', 'username', 'real_name', 'email');
            }
        ]);
        
        // 筛选条件
        if (!empty($method)) {
            $query->where('method', $method);
        }
        
        if (!empty($controller)) {
            $query->where('controller', 'like', "%{$controller}%");
        }
        
        if ($isSuccess !== '' && $isSuccess !== null) {
            $query->where('is_success', (int)$isSuccess);
        }
        
        if (!empty($startDate)) {
            $query->where('created_at', '>=', $startDate . ' 00:00:00');
        }
        
        if (!empty($endDate)) {
            $query->where('created_at', '<=', $endDate . ' 23:59:59');
        }
        
        if (!empty($adminId)) {
            $query->where('admin_id', $adminId);
        }
        
        if (!empty($userType)) {
            $query->where('user_type', $userType);
        }
        
        if (!empty($userId)) {
            $query->where('user_id', $userId);
        }
        
        // 按创建时间倒序
        $query->orderBy('created_at', 'desc');
        
        $paginate = $query->paginate($pageSize, ['*'], 'page', $page);
        
        // 格式化数据
        $items = $paginate->items();
        foreach ($items as $item) {
            // 添加操作者信息
            $item->operator_name = $item->operator_name;
            $item->operator_type_text = $item->user_type === 'admin' ? '管理员' : ($item->user_type === 'user' ? '用户' : '访客');
            
            // 格式化请求数据
            if (is_string($item->request_data)) {
                $item->request_data = json_decode($item->request_data, true) ?: [];
            }
            
            // 隐藏关联数据
            unset($item->admin, $item->user);
        }
        
        return dataByPage($paginate);
    }
    
    /**
     * 获取日志详情
     */
    public function getLogDetail(Request $request)
    {
        $id = $request->get('id');
        
        if (empty($id)) {
            return fail('参数错误');
        }
        
        $log = OperationLogModel::with('admin:id,username,real_name')->find($id);
        
        if (!$log) {
            return fail('日志不存在');
        }
        
        // 添加管理员信息
        $log->admin_name = $log->admin ? ($log->admin->real_name ?: $log->admin->username) : '系统';
        
        // 格式化请求数据
        if (is_string($log->request_data)) {
            $log->request_data = json_decode($log->request_data, true) ?: [];
        }
        
        // 隐藏关联数据
        unset($log->admin);
        
        return data($log);
    }
    
    /**
     * 清理日志
     */
    public function clearLogs(Request $request)
    {
        $params = $request->post();
        
        // 判断是否清理全部日志
        if (isset($params['all']) && $params['all']) {
            $count = OperationLogModel::query()->delete();
            return success("成功清理所有日志记录，共 {$count} 条");
        }
        
        // 按天数清理
        $days = $params['days'] ?? 30; // 默认清理30天前的日志
        
        if ($days < 1) {
            return fail('清理天数必须大于0');
        }
        
        $date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        $count = OperationLogModel::where('created_at', '<', $date)->delete();
        
        return success("成功清理 {$count} 条日志记录");
    }
    
    /**
     * 获取统计数据
     */
    public function getStatistics(Request $request)
    {
        $params = $request->get();
        $days = $params['days'] ?? 7; // 默认7天
        
        $startDate = date('Y-m-d 00:00:00', strtotime("-{$days} days"));
        $endDate = date('Y-m-d 23:59:59');
        
        $query = OperationLogModel::where('created_at', '>=', $startDate)
            ->where('created_at', '<=', $endDate);
        
        // 如果指定了用户类型，则筛选
        if (!empty($params['user_type'])) {
            $query->where('user_type', $params['user_type']);
        }
        
        // 总请求数
        $totalRequests = (clone $query)->count();
        
        // 成功请求数
        $successRequests = (clone $query)->where('is_success', 1)->count();
        
        // 失败请求数
        $failedRequests = $totalRequests - $successRequests;
        
        // 成功率
        $successRate = $totalRequests > 0 ? round(($successRequests / $totalRequests) * 100, 2) : 0;
        
        // 平均响应时间
        $avgDuration = (clone $query)->avg('duration');
        $avgDuration = $avgDuration ? round($avgDuration, 2) : 0;
        
        // 按方法统计
        $methodQuery = OperationLogModel::where('created_at', '>=', $startDate)
            ->where('created_at', '<=', $endDate)
            ->selectRaw('method, COUNT(*) as count');
        if (!empty($params['user_type'])) {
            $methodQuery->where('user_type', $params['user_type']);
        }
        $methodStats = $methodQuery->groupBy('method')->get();
        
        // 按天统计
        $dailyQuery = OperationLogModel::where('created_at', '>=', $startDate)
            ->where('created_at', '<=', $endDate)
            ->selectRaw('DATE(created_at) as date, COUNT(*) as total, SUM(is_success) as success');
        if (!empty($params['user_type'])) {
            $dailyQuery->where('user_type', $params['user_type']);
        }
        $dailyStats = $dailyQuery->groupBy('date')
            ->orderBy('date')
            ->get();
        
        // 用户类型统计
        $userTypeStats = OperationLogModel::where('created_at', '>=', $startDate)
            ->where('created_at', '<=', $endDate)
            ->selectRaw('user_type, COUNT(*) as count')
            ->groupBy('user_type')
            ->orderBy('count', 'desc')
            ->get();
        
        return data([
            'total_requests' => $totalRequests,
            'success_requests' => $successRequests,
            'failed_requests' => $failedRequests,
            'success_rate' => $successRate,
            'avg_duration' => $avgDuration,
            'method_stats' => $methodStats,
            'daily_stats' => $dailyStats,
            'user_type_stats' => $userTypeStats
        ]);
    }
}